package com.xingzhe.ucenter.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xingzhe.ucenter.feignclient.CheckCodeClient;
import com.xingzhe.ucenter.mapper.XcUserMapper;
import com.xingzhe.ucenter.mapper.XcUserRoleMapper;
import com.xingzhe.ucenter.model.dto.AuthParamsDto;
import com.xingzhe.ucenter.model.dto.RegisterDto;
import com.xingzhe.ucenter.model.dto.RetrieveDto;
import com.xingzhe.ucenter.model.po.XcUser;
import com.xingzhe.ucenter.model.po.XcUserRole;
import com.xingzhe.ucenter.service.RetrieveOrRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Service
public class RetrieveOrRegisterImpl implements RetrieveOrRegisterService {
    @Resource
    RestTemplate restTemplate;

    @Resource
    XcUserRoleMapper xcUserRoleMapper;


    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    XcUserMapper xcUserMapper;

    @Transactional
    @Override
    public void retrieve(RetrieveDto authParamsDto) {
        if (authParamsDto==null){
            throw new RuntimeException("没有输入任何参数");
        }
        String cellphone = authParamsDto.getCellphone();
        String email = authParamsDto.getEmail();
        String checkcode = authParamsDto.getCheckcode();

        if (cellphone.isEmpty()&&email.isEmpty()){
            throw new RuntimeException("请至少输入手机号或者邮箱");
        }
        if (!email.isEmpty()&&!cellphone.isEmpty()){
            Boolean verify = verify(cellphone, checkcode);
            if (!verify){
                throw new RuntimeException("验证码错误");
            }
        }else if (email.isEmpty()){
            Boolean verify = verify(cellphone, checkcode);
            if (!verify){
                throw new RuntimeException("验证码错误");
            }
        }else {
            String code = stringRedisTemplate.opsForValue().get(email);
            if (!checkcode.equals(code)){
                throw new RuntimeException("验证码错误");
            }
        }
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        if (!cellphone.isEmpty()){
            queryWrapper.eq(XcUser::getCellphone,cellphone);
        }else {
            queryWrapper.eq(XcUser::getEmail,email);
        }
        XcUser xcUser = xcUserMapper.selectOne(queryWrapper);
        try {
            xcUser.setPassword(authParamsDto.getPassword());
        }catch (Exception e){
            e.printStackTrace();
            log.error("没有该用户！");
        }
        xcUserMapper.updateById(xcUser);

    }

    @Transactional
    @Override
    public void register(RegisterDto authParamsDto) {
        if (authParamsDto.getCheckcode().isEmpty()){
            throw new RuntimeException("验证码为空！");
        }
        if (authParamsDto.getCellphone().isEmpty()){
            throw new RuntimeException("手机号为空！");
        }
        String cellphone = authParamsDto.getCellphone();
       // verify(cellphone,authParamsDto.getCheckcode());
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcUser::getCellphone,cellphone);
        XcUser xcUser1 = xcUserMapper.selectOne(queryWrapper);
        if (xcUser1!=null){
            throw new RuntimeException("已经注册过啦！");
        }
        XcUser xcUser = new XcUser();
        BeanUtils.copyProperties(authParamsDto,xcUser);
        xcUser.setName(authParamsDto.getNickname());
        xcUser.setCreateTime(LocalDateTime.now());
        xcUser.setStatus("1");
        xcUser.setUtype("101001");//学生


        xcUserMapper.insert(xcUser);
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setRoleId("17");//学生
        xcUserRole.setUserId(xcUser.getId());
        xcUserRole.setCreateTime(LocalDateTime.now());
        xcUserRoleMapper.insert(xcUserRole);
    }
    // http://neteasymusic.xiongsihao.com/captcha/verify?phone=%s&captcha=1597
    public Boolean verify(String phone,String code){
        String wxUrl_template = "http://neteasymusic.xiongsihao.com/captcha/verify?phone=%s&captcha=%s";

        String wxUrl = String.format(wxUrl_template,phone,code);

        log.info("调用网易云接口校验验证码, url:{}", wxUrl);

        try {
            ResponseEntity<String> exchange = restTemplate.exchange(wxUrl, HttpMethod.GET, null, String.class);
            String result = new     String(exchange.getBody().getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
            log.info("调用微信接口申请access_token: 返回值:{}", result);
            Map<String,String> resultMap = JSON.parseObject(result, Map.class);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            log.debug("校验验证码错误");
        }
        return false;
    }
}
